<?php

defined('SYSPATH') or die('No direct access allowed.');

class Kohana_Alipay_Service extends Alipay {

    /**
     * @var array 构建表单的参数
     */
    protected $parameter;

    /**
     * 构造方法
     * 
     * @var array 参与签名的参数
     */
    public function __construct($parameter) {
        //父类构造方法
        parent::__construct();
        //定义通用的参数
        $parameter['return_url'] = $this->_config['pay_return_url'];
        $parameter['notify_url'] = $this->_config['notify_url'];
        $parameter['show_url'] = $this->_config['show_url'];
        $parameter['_input_charset'] = $this->input_charset;
        $parameter['partner'] = $this->partner;
        $parameter['seller_email'] = $this->_config['seller_email'];

        //过滤掉空的或签名的字段
        $parameter = $this->para_filter($parameter);
        //获得签名结果
        $this->parameter = $this->arg_sort($parameter); //得到从字母a到z排序后的签名参数数组
        $this->mysign = $this->build_mysign($this->parameter, $this->key, $this->sign_type);
    }

    /**
     * 构造表单提交HTML
     *
     * @param array 要提交的参数
     * @param string 表单提交方法
     * @return string 表单提交HTML文本
     */
    public function build_form($method = 'GET', $auto_submit = TRUE) {
        
        $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='" . $this->gateway .
                "_input_charset=" . $this->parameter['_input_charset'] . "' method='$method'>";

        while (list ($key, $val) = each($this->parameter)) {
            $sHtml.= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
        }

        $sHtml = $sHtml . "<input type='hidden' name='sign' value='" . $this->mysign . "'/>";
        $sHtml = $sHtml . "<input type='hidden' name='sign_type' value='" . $this->sign_type . "'/>";

        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml . "<input type='submit' value='支付宝确认付款'></form>";

        if ($auto_submit) {
            $sHtml = $sHtml . "<script>document.forms['alipaysubmit'].submit();</script>";
        }

        return $sHtml;
    }

}